package com.pxmeta.dynamic.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.pxmeta.circle.entity.Circle;
import com.pxmeta.circle.service.ICircleService;
import com.pxmeta.common.constant.HttpStatus;
import com.pxmeta.common.enums.DynamicEnum;
import com.pxmeta.common.exception.ServiceException;
import com.pxmeta.common.utils.StringUtils;
import com.pxmeta.dynamic.entity.Dynamic;
import com.pxmeta.dynamic.entity.Topic;
import com.pxmeta.dynamic.entity.SearchHistory;
import com.pxmeta.dynamic.entity.TopicDynamic;
import com.pxmeta.dynamic.entity.dto.TopicDTO;
import com.pxmeta.dynamic.mapper.DynamicMapper;
import com.pxmeta.dynamic.mapper.TopicMapper;
import com.pxmeta.dynamic.service.*;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 社区评论Service业务层处理
 *
 * @author wcl
 * @date 2022-03-21
 */
@Service
@SuppressWarnings("all")
public class TopicServiceImpl extends ServiceImpl<TopicMapper, Topic> implements ITopicService
{
    @Autowired
    private TopicMapper topicMapper;

    @Autowired
    private ISearchHistoryService searchHistoryService;

    @Autowired
    private ICircleService circleService;

    @Autowired
    private ITopicDynamicService topicDynamicService;

    @Autowired
    private ITopicUserFollowService topicUserFollowService;

    @Autowired
    private DynamicMapper dynamicMapper;

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public Topic add(TopicDTO dto, Long userId) {
        Topic topic = new Topic();
        Long circleId = dto.getCircleId();
        Circle circle = circleService.getById(circleId);
        if (null == circle){
            throw new ServiceException("圈子不存在！");
        }
        topic.setCircleId(circleId);
        String name = dto.getName();
        topic.setName(name);
        topic.setCircleType(circle.getType());
        topic.setUserCount(1L);
        SearchHistory searchHistory = new SearchHistory();
        searchHistoryService.saveSearch(userId,circleId,name, DynamicEnum.TYPE_TOPIC.getType());
        this.save(topic);
        return topic;
    }

    @Override
    public List<TopicDTO> search(Long userId, Long circleId, String name) {
        if (StringUtils.isBlank(name)){
            throw new ServiceException("话题名称不能为空！", HttpStatus.PARAMS_ERROR);
        }
        //保存搜索历史记录
        searchHistoryService.saveSearch(userId,circleId,name,DynamicEnum.TYPE_TOPIC.getType());
        LambdaQueryWrapper<Topic> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Topic::getCircleId, circleId)
                .like(Topic::getName, name)
                .orderByDesc(Topic::getUserCount);
        List<Topic> topicList = this.list(wrapper);
        List<Long> topicIds = topicList.stream().map(Topic::getId).collect(Collectors.toList());

        List<Long> followTopicIds = topicUserFollowService.getFollowTopicIds(userId, topicIds);
        return topicList.stream().map(topic->{
            TopicDTO dto = new TopicDTO();
            Long id = topic.getId();
            dto.setIsFollow(followTopicIds.contains(id));
            dto.setName(topic.getName());
            dto.setCircleId(topic.getCircleId());
            Long dynamicCount = topicDynamicService.getDynamicCount(id);
            dto.setDynamicCount(dynamicCount);
            dto.setViewCount(topic.getViewCount());
            dto.setId(id);
            return dto;
        }).collect(Collectors.toList());
    }

    /**
     * 根据分类id获取话题列表
     * @param circleId
     * @param categoryId
     * @return
     */
    @Override
    public List<TopicDTO> getByCategoryId(Long userId, Long circleId, Long categoryId) {

        Circle circle = circleService.getById(circleId);
        if (null == circle){
            throw new ServiceException("圈子不存在！");
        }
        LambdaQueryWrapper<Topic> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Topic::getCircleType,circle.getType())
                .eq(Topic::getCategoryId, categoryId)
                .orderByDesc(Topic::getUserCount)
                .last("limit 30");
        List<Topic> topicList = this.list(wrapper);
        List<Long> topicIds = topicList.stream().map(Topic::getId).collect(Collectors.toList());
        List<Long> followTopicIds = topicUserFollowService.getFollowTopicIds(userId, topicIds);

        List<TopicDTO> list = topicList.stream().map(l -> {
            TopicDTO dto = new TopicDTO();
            Long topicId = l.getId();
            dto.setId(topicId);
            dto.setCircleId(l.getCircleId());
            dto.setIsFollow(followTopicIds.contains(topicId));
            dto.setViewCount(l.getViewCount());
            dto.setName(l.getName());
            Long dynamicCount = topicDynamicService.getDynamicCount(topicId);
            dto.setDynamicCount(dynamicCount);
            return dto;
        }).collect(Collectors.toList());
        return list;
    }

    @Override
    public List<TopicDTO> getHotTopicByCircle(Long userId, Long circleId){
        Circle circle = circleService.getById(circleId);
        Integer type = circle.getType();
        LambdaQueryWrapper<Topic> wrapper = Wrappers.lambdaQuery();
//        wrapper.eq(Topic::getCircleType, circleId)
//                .orderByDesc(Topic::getViewCount);
//
//        long topicCount = this.count(wrapper);
//        if (topicCount < 5){ //如果圈子下话题数小于5个，则根据分类查询。
//            wrapper.clear();
//            wrapper.eq(Topic::getCircleType, type)
//                    .orderByDesc(Topic::getViewCount);
//        }
        if (type!=0){
            wrapper.eq(Topic::getCircleId, circleId);
        }
        wrapper.orderByDesc(Topic::getViewCount);
        wrapper.last("limit 5");
        List<Topic> topicList = this.list(wrapper);
        List<Long> topicIds = topicList.stream().map(Topic::getId).collect(Collectors.toList());
        List<Long> followTopicIds = topicUserFollowService.getFollowTopicIds(userId, topicIds);
        List<TopicDTO> list = topicList.stream().map(topic -> {
            TopicDTO dto = new TopicDTO();
            Long id = topic.getId();
            dto.setIsFollow(followTopicIds.contains(id));
            dto.setId(id);
            dto.setCircleId(topic.getCircleId());
            dto.setViewCount(topic.getViewCount());
            dto.setName(topic.getName());
            Long dynamicCount = topicDynamicService.getDynamicCount(id);
            dto.setDynamicCount(dynamicCount);
            dto.setImgUrl(topic.getImgUrl());
            return dto;
        }).collect(Collectors.toList());

        return list;
    }


    /**
     * 获取话题列表
     * @param page
     * @param size
     * @param keyword
     * @return
     */
    @Override
    public IPage<TopicDTO> getList(Integer page, Integer size, String keyword, Integer type, Long categoryId) {
        return baseMapper.getPage(new Page<>(page, size), type, keyword, categoryId);
    }

    @Override
    public void deleteTopic(Long id) {
        LambdaQueryWrapper<TopicDynamic> topicDynamicWrapper = Wrappers.lambdaQuery();
        topicDynamicWrapper.eq(TopicDynamic::getTopicId,id);
        List<Long> dynamicIds = topicDynamicService.list(topicDynamicWrapper).stream().map(TopicDynamic::getDynamicId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(dynamicIds)){
            for (Long dynamicId : dynamicIds) {
                Dynamic dynamic = new Dynamic();
                dynamic.setId(dynamicId);
                dynamic.setTopicIds("");
                dynamicMapper.updateById(dynamic);
            }

            topicDynamicService.remove(topicDynamicWrapper);
        }
        this.removeById(id);
    }

}
